/*
 *     This file is part of Mobile GPS Logger.
 *
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 *
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */

package cx.ath.skyflyer.gpslog.nmea;

import cx.ath.skyflyer.gpslog.util.Tokenizer;
import java.util.NoSuchElementException;

/**
 *
 * @author Ahti Legonkov
 */
public class GroundSpeed extends NmeaSentence {

    public static String PREFIX = "$GPVTG";

    public GroundSpeed(String gpvtg) 
            throws IllegalArgumentException
            , UnsupportedTypeException
            , NoSuchElementException
            , ChecksumMismatchException
    {
        super(gpvtg);
        parser = new Tokenizer(gpvtg);
        String id = parser.next();
        if (!id.equals(PREFIX)) {
            throw new UnsupportedTypeException(PREFIX, id);
        }
    }

    public double getGroundSpeedKmh() {
        if (!parsed)
            parse();

        return groundSpeedKmh;
    }

    public double getGroundSpeedKnots() {
        if (!parsed)
            parse();

        return groundSpeedKnots;
    }

    public String getMagneticCourse() {
        if (!parsed)
            parse();

        return magneticCourse;
    }

    public String getTrueCourse() {
        if (!parsed)
            parse();

        return trueCourse;
    }

    /**
     *
     * @param speed a string representation of speed.
     * @param unit units that the speed is measured in. K - km/h, N - knots.
     * @throws java.lang.IllegalArgumentException if unit is neither K or N.
     */
    private void assignSpeed(String speed, String unit)
            throws IllegalArgumentException {
        double s = Double.parseDouble(speed);

        if (unit.equals("K"))
            groundSpeedKmh = s;
        else if (unit.equals("N"))
            groundSpeedKnots = s;
        else
            throw new IllegalArgumentException();
    }

    private void parse() {
        trueCourse = parser.next();
        parser.next();
        magneticCourse = parser.next();
        parser.next();
        assignSpeed(parser.next(), parser.next());
        assignSpeed(parser.next(), parser.next());
        parsed = true;
    }

    private Tokenizer parser;
    private String trueCourse;
    private String magneticCourse;
    private double groundSpeedKmh;
    private double groundSpeedKnots;
    private boolean parsed = false;
}
